<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AIA_Controller extends CI_Controller {

    protected $_controller;
    protected $_action;
    protected $_api_config;

    function __construct() {
        parent::__construct();

        $this->_controller = $this->uri->segment(1, 'index');
        $this->_action = $this->uri->segment(2, '');

        $this->_api_config = $this->_get_api_config();
    }

    protected function _get_api_config() {
        $this->load->config('api', TRUE, TRUE);
        return $this->config->item('api');
    }

    public function load_resource() {
        $this->config->load('static', TRUE, TRUE);
        $static = $this->config->item('static');
        $resource = array(
            'css' => array(),
            'js' => array()
        );
        $uri = $this->_controller . ($this->_action ? '/' . $this->_action : '');
        foreach ($static['css']['public'] as $item) {
            $resource['css'][] = $this->_is_url($item) ? $item : base_url($item);
        }
        foreach ($static['js']['public'] as $item) {
            $resource['js'][] = $this->_is_url($item) ? $item : base_url($item);
        }
        if (array_key_exists($uri, $static['css']['page'])) {
            $row = $static['css']['page'][$uri];
            foreach ($row as $item) {
                $resource['css'][] = $this->_is_url($item) ? $item : base_url($item);
            }
        }
        if (array_key_exists($uri, $static['js']['page'])) {
            $row = $static['js']['page'][$uri];
            foreach ($row as $item) {
                $resource['js'][] = $this->_is_url($item) ? $item : base_url($item);
            }
        }
        $this->load->vars($resource);
        // $this->load->vars($this->_wx_js_sdk_config());
    }

    public function ajax_request($method) {
        
        if ($this->input->is_ajax_request()) {

            if ($this->input->post(NULL, TRUE)) {
                $request = $this->input->post(NULL, TRUE);
            } else {
                $request = $this->input->get(NULL, TRUE);
            }
            $this->$method($request);
        } else {    
            show_404();
        }
    }

    protected function _curl_request($type, $url, $data = array(), $options = array()) {
        $this->load->library('curl');

        $method = (strtolower($type) === 'get') ? 'simple_get' : 'simple_' . strtolower($type);
        $url = $this->_is_url($url) ? $url : $this->_api_config['platform']['server'] . $url;

        return json_decode($this->curl->$method($url, $data, $options), TRUE);       
    }

    protected function _set_cookie($name, $value, $expire = 86500) {
        $cookie = array(
            'name'   => $name,
            'value'  => $value,
            'expire' => $expire,        // 有效时间为1天
            'domain' => ltrim(rtrim(base_url(), '/'), 'http://')
        );

        return $this->input->set_cookie($cookie);
    }

    protected function _del_cookie($name) {
        $cookie = array(
            'name' => $name,
            'domain' => ltrim(rtrim(base_url(), '/'), 'http://')
        );

        $this->load->helper('cookie');
        delete_cookie($cookie);
    }

    private function _is_url($str) {
        $pattern = '@(((https?|ftp):)?//([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@';
        return preg_match($pattern, $str);
    }

    protected function _get_wx_access_token() {
        $wx_access_token = apc_fetch('wx_access_token');
        // $wx_access_token = FALSE;
        if (!$wx_access_token) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $data = array(
                'grant_type' => 'client_credential',
                'appid' => $this->_api_config['weixin']['appid'],
                'secret' => $this->_api_config['weixin']['secret']
            );
            $result = $this->_curl_request('get', $url, $data);
            apc_store('wx_access_token', $result['access_token'], $result['expires_in']);
            // apc_store('wx_access_token', $result['access_token'], 1800);
            $wx_access_token = $result['access_token'];
        }
        return $wx_access_token;
    }

    protected function _get_wx_jsapi_ticket() {
        $wx_jsapi_ticket = apc_fetch('wx_jsapi_ticket');
        // $wx_jsapi_ticket = FALSE;
        if (!$wx_jsapi_ticket) {
            $wx_access_token = $this->_get_wx_access_token();
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
            $data = array(
                'access_token' => $wx_access_token,
                'type' => 'jsapi'
            );
            $result = $this->_curl_request('get', $url, $data);
            apc_store('wx_jsapi_ticket', $result['ticket'], $result['expires_in']);
            $wx_jsapi_ticket = $result['ticket'];
        }
        return $wx_jsapi_ticket;
    }

    protected function _generate_random_str($length = 5) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = 'aia' . date('YmdHis');

        for ($i=0; $i < $length; $i++) { 
            $code .= $chars[mt_rand(0, strlen($chars)-1)];
        }
        return $code;
    }

    protected function _wx_js_sdk_config() {
        $wx_jsapi_ticket = $this->_get_wx_jsapi_ticket();
        $wx_noncestr = $this->_generate_random_str();
        $timestamp = time();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $query_string = "jsapi_ticket={$wx_jsapi_ticket}&noncestr={$wx_noncestr}&timestamp={$timestamp}&url={$url}";
        $sign = sha1($query_string);
        $data = array(
            'wx_jssdk_config' => array(
                'appid' => $this->_api_config['weixin']['appid'],
                'timestamp' => $timestamp,
                'noncestr' => $wx_noncestr,
                'signature' => $sign
            )
        );
        return $data;
    }

    protected function _check_user() {
        redirect('share');
        $user = $this->_get_current_user();

        if (!$user) {
            $url = 'http://im.189.cn/weixinopen/outserver/oauth/getOpenid';
            $url .= '?url=';
            $url .= base64_encode($this->_api_config['telecom']['redirect_url']);
            redirect($url);
        } else {
            // $data = array(
            //     'user' => $user
            // );
            // $this->load->vars($data);
        }
    }

    protected function _set_user($request) {
        $data = array(
            'user' => $request['openid']
            // 'nickname' => $request['nickname']
        );
        $this->load->library('session');
        $this->session->set_userdata($data);
    }

    protected function _get_current_user() {
        $this->load->library('session');
        $user = $this->session->userdata('user');
        if (!$user) {
            return FALSE;
        } else {
            return $user;
        }
    }
    
    protected function _get_user_prize() {
        $user = $this->_get_current_user();
        $this->load->model('Ct_model');
        return $this->Ct_model->get_user_prize($user);
    }

}

/* End of file HORSE_Controller.php */
/* Location: ./application/core/HORSE_Controller.php */